<template>
  <img :src="src" ref="img" alt="" />
</template>
<script lang="ts" setup>
import { onMounted, ref, defineProps } from 'vue'

const img: any = ref(null)
//loading加载的图片
const src: any = ref('https://n.sinaimg.cn/sinacn/w800h800/20180111/4ab1-fyqnick7504844.gif')
const props = defineProps(['dataSrc'])
//判断图片是加载成功还是失败
const tususs = () => {
  //创建一个新的Image对象，设置其src属性为传入的props.dataSrc
  const newimg = new Image()
  newimg.src = props.dataSrc
  //添加load事件监听器
  newimg.addEventListener('load', () => {
    img.value!.src = props.dataSrc
  })
  newimg.addEventListener('error', () => {
    img.value!.src = 'https://pic.616pic.com/ys_bnew_img/00/11/97/pGPYIRzYFE.jpg'
  })
}

//判断是否进入可视化区域
onMounted(() => {
  if (img.value) {
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].intersectionRatio <= 0) return
      //加载图片
      tususs()
      //取消监听
      observer.unobserve(img.value!)
    })
    //作为目标进行观察
    observer.observe(img.value!)
  }
})
</script>
<style scoped></style>
